import { BrowserWindow, desktopCapturer, ipcMain } from 'electron';
import { join } from 'path';
import icon from '../../../resources/icon.png?asset';
import { is } from '@electron-toolkit/utils';
import { getSize } from '../utils';

let childrenWindow: BrowserWindow | null = null;
export const screenCapture = (path: string) => {
  // 获取主屏幕的分辨率
  const { width, height } = getSize();
  childrenWindow = new BrowserWindow({
    width,
    height,
    show: false,
    transparent: true,
    autoHideMenuBar: true,
    titleBarStyle: 'hidden',
    ...(process.platform === 'linux' ? { icon } : { icon }),
    webPreferences: {
      preload: join(__dirname, '../preload/index.js'),
      sandbox: false
    }
  });
  childrenWindow.on('ready-to-show', () => {
    childrenWindow?.webContents.openDevTools({ mode: 'detach' });
    childrenWindow?.webContents.send('children-window-call', path);
    childrenWindow?.show();
  });

  if (is.dev && process.env['ELECTRON_RENDERER_URL']) {
    childrenWindow.loadURL(process.env['ELECTRON_RENDERER_URL']);
  } else {
    childrenWindow.loadFile(join(__dirname, '../renderer/index.html'));
  }

  childrenWindow.maximize();
  childrenWindow.setFullScreen(true);

  ipcMain.on(
    'set-capture-window-size',
    (
      _: any,
      item: { top: number; left: number; width?: number; height?: number }
    ) => {
      childrenWindow?.hide();
      childrenWindow?.setPosition(item.left || 0, item.top || 0);
      if (item.width && item.height) {
        childrenWindow?.setSize(item.width, item.height);
      } else {
        const size = childrenWindow?.getSize();
        if (width !== size?.[0] || height !== size?.[1]) {
          childrenWindow?.setSize(width, height);
        }
      }
      childrenWindow?.show();
    }
  );
  ipcMain.once(
    'catch-screen-capture',
    async (context: Electron.IpcMainEvent) => {
      console.log('🚀 ~ ipcMain.on ~ catch-screen-capture:');
      const sources = await desktopCapturer.getSources({
        types: ['screen'],
        thumbnailSize: getSize()
      });
      const source = sources[0];
      const base64Url = await source.thumbnail.toDataURL();
      context.reply('catch-screen-capture-call', base64Url);
    }
  );
  return childrenWindow;
};

export const screenCaptureClose = () => {
  if (!childrenWindow) return;
  childrenWindow?.destroy();
  childrenWindow = null;
};
